import axios from 'axios';
import {PcCookie, Key} from '@/utils/cookie';
import store from "@/store";

const request = axios.create({
  //baseURL:process.env.VUE_APP_SERVICE_URL,
  baseURL: '/dev-api', // url = base url + request url
  timeout: 15000,// 请求超时 15秒
  headers:{
    'Content-Type':"application/json;charset=uft-8"
  },
  withCredentials:true,// 允许跨域
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const accessToken = PcCookie.get(Key.accessTokenKey);
    if (accessToken) {
      config.headers.Authorization = `Bearer ${accessToken}`
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)


//响应拦截器
request.interceptors.response.use(response =>{
  return response.data;

  /*if(res.code === 200) {
    return response.data;
  } else if(res.code === 408) {
    Element.Message.error('该用户未注册')
  } else {
    Element.Message.error(!res.msg ? '系统异常' : res.msg)
    return Promise.reject(response.data.msg);
  }*/
},error =>{
  console.log("出现异常"+error)
  if(error.response.status === 401){
    PcCookie.remove(Key.userInfoKey);
    PcCookie.remove(Key.accessTokenKey);
    PcCookie.remove(Key.refreshTokenKey);
    window.location.href = `http://localhost:9999`;
    //window.location.href = `http://admin.r2blog.cn`;
    // return Promise.reject(error)
    /*alert("身份过期，请重新登录")
    return Promise.reject(error)*/
  }
  // 401 发送刷新令牌获取新令牌
  // sendRefreshRequest(store);
  /*return Promise.reject('令牌过期，重新登录')*/
})

/*let isLock = true;//防止并发重复发送

const sendRefreshRequest = (store) =>{
  if(isLock && store.state.refreshToken){
    isLock = false;
    // 发送请求到认证客户端
    window.location.href = `${loginURL}/refresh?redirectURL=${window.location.href}`;
  }else{
    isLock = true;
    store.commit('setUserInfo',null);
    store.commit('setAccessToken',null);
    store.commit('setRefreshToken',null);
    window.location.href = `${loginURL}/?redirectURL=${window.location.href}`;
  }
}*/


//导出自定义创建的axios对象
export default request
